package com.xiguaji.tiktok.v1.ins.rank.repository.impl;

import com.xiguaji.boot.toolkit.jdbc.JdbcTemplateHelper;
import com.xiguaji.boot.toolkit.jdbc.Page;
import com.xiguaji.tiktok.v1.ins.rank.dto.InsRkSearch;
import com.xiguaji.tiktok.v1.ins.rank.dto.ProductRankDto;
import com.xiguaji.tiktok.v1.ins.rank.repository.InsRkProductMonthExtRepository;
import io.micrometer.core.instrument.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class InsRkProductMonthExtRepositoryImpl implements InsRkProductMonthExtRepository {

    @Override
    public Page<ProductRankDto> getPage(InsRkSearch insRkSearch) {
        List<Object> params = new ArrayList<>();
        StringBuilder selectSql = new StringBuilder("select rp.rank,rp.influencer_count,rp.media_count,rp.tec,");
        selectSql.append(" p.id,p.product_id,p.merchant_uid,p.product_name,p.price,p.current_price,p.full_price,p.current_price_stripped,p.image,p.overall_category_name,");
        selectSql.append(" b.username,b.full_name,b.is_verified,b.pic_url ");
        StringBuilder fromSql = new StringBuilder();
        fromSql.append("from ins_rk_product_month rp left join ins_product p on rp.product_id = p.product_id ");
        fromSql.append("left join ins_blogger b on p.merchant_uid = b.uid ");
        fromSql.append("where datecode = ? ");
        params.add(insRkSearch.getDate());

        if(StringUtils.isNotEmpty(insRkSearch.getCategoryName())){
            fromSql.append("and rp.category_name = ? ");
            params.add(insRkSearch.getCategoryName());
        }
        fromSql.append("order by rp.rank");
        return JdbcTemplateHelper.paginate(ProductRankDto.class,insRkSearch.getPage(),insRkSearch.getPageSize(),selectSql.toString(),fromSql.toString(),params.toArray());
    }

    @Override
    public List<ProductRankDto> getList(InsRkSearch insRkSearch,int size) {
        List<Object> params = new ArrayList<>();
        StringBuilder sql = new StringBuilder("select rp.rank,rp.influencer_count,rp.media_count,rp.tec,");
        sql.append("p.id,p.product_id,p.merchant_uid,p.product_name,p.price,p.current_price,p.full_price,p.current_price_stripped,p.image,p.overall_category_name,");
        sql.append("b.username,b.full_name,b.is_verified,b.pic_url ");
        sql.append("from ins_rk_product_month rp left join ins_product p on rp.product_id = p.product_id ");
        sql.append("left join ins_blogger b on p.merchant_uid = b.uid ");
        sql.append("where datecode = ? ");
        params.add(insRkSearch.getDate());

        if(StringUtils.isNotEmpty(insRkSearch.getCategoryName())){
            sql.append("and rp.category_name = ? ");
            params.add(insRkSearch.getCategoryName());
        }
        sql.append("order by rp.rank limit 0,?");
        params.add(size);
        return JdbcTemplateHelper.findEntity(ProductRankDto.class,sql.toString(),params.toArray());
    }
}
